from socket import *
import json
from time import sleep
num = 0
location_last = None
class tcp:
    tcp_client_socket = None  # 类属性用于存储客户端 socket 对象
    @staticmethod
    def enable(server_ip: str, server_port: int):
        try:
            # 创建 TCP socket 并连接到服务器
            tcp.tcp_client_socket = socket(AF_INET, SOCK_STREAM)
            tcp.tcp_client_socket.connect((server_ip, server_port))
            print(f"成功连接到服务器 {server_ip}:{server_port}")
            return "成功连接"
        except Exception as e:
            print(f"连接服务器 {server_ip}:{server_port} 失败:", e)
            return "无法连接"
    @staticmethod
    def disable():
        if tcp.tcp_client_socket:
            tcp.tcp_client_socket.close()
            print("成功关闭连接")
        else:
            print("未建立连接，无需关闭")
    @staticmethod
    def send(send_data):
        if tcp.tcp_client_socket:
            try:
                tcp.tcp_client_socket.send(send_data.encode("utf-8"))
                print(f"发送数据成功: {send_data}")
            except Exception as e:
                print("发送数据失败:", e)
        else:
            print("未建立连接，无法发送数据")
    @staticmethod

    def recv(max_retries=10):
        if tcp.tcp_client_socket:
            try:
                retries = 0
                while retries < max_retries:
                    global recvStr
                    recvData = tcp.tcp_client_socket.recv(1024)
                    recvStr = recvData.decode('utf-8').strip()  # 移除字符串两端的空白字符
                    print(f'原始接收到的数据为: {recvStr}')

                    if len(recvStr) <= 6:
                        print("接收到的数据长度小于等于6，重新接收...")
                        tcp.send("1")
                        retries += 1
                        continue

                    location = json.loads(f'[{recvStr}]')
                    recvStr = None
                    print(f'接收到的数据为: {location}')
                    return location

                print("达到最大重试次数，接收数据失败")
            except Exception as e:
                print("接收数据失败:", e)
        else:
            print("未建立连接，无法接收数据")
    # def recv(max_retries=10):
    #     if tcp.tcp_client_socket:
    #         try:
    #             retries = 0
    #             while retries < max_retries:
    #                 recvData = tcp.tcp_client_socket.recv(1024)
    #                 recvStr = recvData.decode('utf-8').strip()  # 移除字符串两端的空白字符
    #                 print(f'原始接收到的数据为: {recvStr}')
    #
    #                 if len(recvStr) <= 6:
    #                     print("接收到的数据长度小于等于6，重新接收...")
    #                     tcp.send("1")
    #                     retries += 1
    #                     continue
    #
    #                 try:
    #                     location = json.loads(f'[{recvStr}]')
    #                 except json.JSONDecodeError:
    #                     print("JSON解析失败")
    #                     retries += 1
    #                     continue
    #
    #                 global location_last # 使用全局变量
    #                 if location_last is None:
    #                     location_last = location.copy()
    #                 else:
    #                     x = location_last[1] - location[1]
    #                     y = location_last[2] - location[2]
    #                     location_last = location.copy()
    #                     if abs(x) <= 10 and abs(y) <= 10:  # 使用绝对值比较
    #                         sleep(1.5)
    #                         tcp.send("1")
    #                         continue
    #
    #                 print(f'接收到的数据为: {location}')
    #                 return location
    #
    #             print("达到最大重试次数，接收数据失败")
    #         except Exception as e:
    #             print("接收数据失败:", e)
    #     else:
    #         print("未建立连接，无法接收数据")
